package com.example.cachedemo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网络相关工具，比如图片下载
 */
public final class NetworkUtil {
    // Buffer大小,8K;
    private static int IO_BUFFER_SIZE = 8 * 1024;

    /**
     * 将图片下载到本地输出流；
     * @param urlString      图片url
     * @param outputStream   本地输出流
     * @return               下载是否成功
     */
    public static boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection)url.openConnection();

            out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);
            in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e){
            e.printStackTrace();;
        } finally {
            try {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 默认不成功
        return false;
    }
}
